package com.ckjava.test.gencode.service.base;

import com.ckjava.test.gencode.dao.base.BaseMybatisCrudDao;
import com.ckjava.test.gencode.entity.base.BaseMybatisEntity;
import com.ckjava.xutils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Transactional(readOnly = true)
public abstract class BaseMybatisCrudService<D extends BaseMybatisCrudDao, E extends BaseMybatisEntity> implements Constants {

    @Autowired
    protected D dao;

    public Optional<List<E>> getAll() {
        return Optional.ofNullable(dao.getAll());
    }

    public Optional<BaseMybatisEntity> get(Long id) {
        return Optional.ofNullable(dao.get(id));
    }

    @Transactional
    public Optional<Long> save(E e) {
        return Optional.ofNullable(dao.save(e));
    }

    @Transactional
    public void update(E e) {
        dao.update(e);
    }

    @Transactional
    public Optional<Long> saveOrUpdate(E e) {
        if (e.getId() == null) {
            return Optional.ofNullable(dao.save(e));
        } else {
            dao.update(e);
            return Optional.ofNullable(e.getId());
        }
    }

    @Transactional
    public Optional<Integer> delete(Long id) {
        return Optional.ofNullable(dao.delete(id));
    }
}
